<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ResponseData;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Plugin\ChuanglanSmsApi;
use App\Http\Requests\LoginRequest;
use App\Models\ActionLog;
use App\Models\CustomerManager;
use App\Models\Department;
use App\Models\SystemUser;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;

class LoginController extends Controller
{
    use ResponseData;
    public function login(Request $request)
    {
        //验证用户账号密码
        $user = SystemUser::query()
            ->with('department')
            ->where('username', $request->username)->first();
        if (! $user || ! Hash::check($request->password, $user->password)) {
            return $this->failed("账号或密码错误!",201);
        }
        if($user->status==2){
            return $this->failed('账号已禁用',201);
        }
        $department = Department::query()->find($user->department_id);
        if($department){
            if($department->status==2){
                return $this->failed('部门已停用，请联系管理员。',201);
            }
        }
        if($user->department_status==2){
            return $this->failed('部门已停用，请联系管理员。',201);
        }
        //记录登录日志
        $this ->actionLog('登录后台',$user->id);
        return $this->UpdateUser($user,$request);
    }
    //客户登录
    public function loginByCode(Request $request)
    {
        if(!preg_match('/^1\d{10}$/', $request->phone)){
            return $this->failed('手机号格式不正确',201);
        }
        $key = 'youfu'.$request->phone;
        $code = Cache::get($key);

        if(!$code){
            return $this->failed('请点击发送验证码',201);
        }else{
            $res=json_decode($code,true);

            if($request->code!=$res['code']){
                return $this->failed('短信验证码错误',201);
            }
        }
        //验证用户账号密码
        $user = CustomerManager::query()
//            ->with('department')
            ->where('login_phone', $request->phone)->first();
        if (! $user) {
            return $this->failed("用户不存在",201);
        }
        if($user->status==2){
            return $this->failed('账号已禁用',201);
        }

        //记录登录日志
        $this ->actionLog('登录后台',$user->id);
        return $this->CustomerUser($user,$request);
    }
    //客户登录
    private function CustomerUser($user,$request){
        $token = $user->createToken($request->phone)->plainTextToken;
        $user->last_login_ip    = $request ->ip();
        $user->last_login_time  = now();
        $user->remember_token   = $token;
        $user->save();
        return [
            'access_token' => 'Bearer '.$token,
            'token_type' => 'Bearer',
            'expires_in' => 1800,
            'refresh_in'=>1800,
            'user_info' => $user
        ];
    }
    //管理员登录
    private function UpdateUser($user,$request){
        $token = $user->createToken($request->username)->plainTextToken;
        $user->last_login_ip    = $request ->ip();
        $user->last_login_time  = now();
        $user->remember_token   = $token;
        $user->save();

        return $this->respondWithToken($token, $user);
    }
    private function respondWithToken($token, $user)
    {
        $roles = Role::query()->whereIn('name',$user->getRoleNames())->pluck('id');
        $userInfo = [
            'id' => $user->id,
            'username' => $user->username,
            'name' => $user->name,
            'roles' =>  $roles??[],
            'department'=>$user->department,
            'type'=>$user->type
        ];
        return [
            'access_token' => 'Bearer '.$token,
            'token_type' => 'Bearer',
            'expires_in' => 1800,
            'refresh_in'=>1800,
            'user_info' => $userInfo
        ];
    }

    //退出登录
    public function logout(Request $request) {
        $user = $request->user();
        if(!$user){
            return $this->failed("退出失败，用户不存在",201);
        }
        $this->actionLog("退出登录",$user->id);
        $user->tokens()->delete();
        return $this->success('退出成功');
    }
    //后台日志
    protected function actionLog($content, $uid = 0)
    {
        if (is_array($content) && !empty($content)) {
            $data = [];
            foreach ($content as $k => $v) {
                $data[] = [
                    'uid' => $uid,
                    'content' => $v,
                    'ip' => request()->ip(),
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'updated_at' => Carbon::now()->toDateTimeString()
                ];
            }

            if (!ActionLog::insert($data)) {
                return false;
            }
            return true;
        } else {
            $data = [
                'uid' => $uid,
                'content' => $content,
                'ip' => request()->ip(),
                'created_at' => Carbon::now()->toDateTimeString(),
                'updated_at' => Carbon::now()->toDateTimeString()
            ];
            if (!ActionLog::insert($data)) {
                return false;
            }
            return true;
        }
    }
    protected function GetAllPremission(Request $request){
        $user = $request->user();
        $permissions = $user->getAllPermissions();

        return $this->success($permissions);
    }

    //发送验证码
    public function smsCode(Request $request){
        $phone = $request->input('phone');
        if(!$phone){
            return $this->failed('手机号必填',201);
        }
        if(!preg_match('/^1\d{10}$/', $phone)){
            return $this->failed('手机号格式不正确',201);
        }
        $key = 'youfu'.$phone;
        $limit = $this->limitPhone($key);
        if(!$limit){
            return $this->failed('今日已超过发送短信次数，请明日再来',201);
        }
        $sms = Cache::get($key);
        if(!$sms){
            $result = $this->sendSms($phone,$key);
        }else{
            $val = json_decode($sms,true);
            if(time()-$val['time']>60){
                $result = $this->sendSms($phone,$key);
            }else{
                return $this->failed('重复获取验证码不得小于60秒',201);
            }
        }
        $decode = json_decode($result,true);
        if($decode['code']!=0){
            return $this->failed($decode['errorMsg'],201);
        }
        return $this->success('验证码发送成功！');
    }
    protected function limitPhone($phone){
        $key = 'limit'.$phone;
        $value = Cache::get($key);
        if($value){
            if($value<5){
                Cache::increment($key);
                return 1;
            }else{
                return 0;
            }
        }else{
            $time = strtotime(date('Y-m-d',strtotime('+1 day')))-time();
            Cache::put($key,1,$time);
            return 1;
        }
    }
    protected function sendSms($phone,$key){
        $app = new ChuanglanSmsApi();
        $code = rand(111111,999999);
        $msg = '您正在进行登录操作，验证码'.$code.'，10分钟内有效，若非本人操作，请勿泄露';
        $result = $app->sendSMS($phone,$msg);
        $value = array(
            'time'=>time(),
            'code'=>$code,
        );
        Cache::put($key,json_encode($value),600);
        return $result;
    }
}
